<?php
namespace app\middleware;

use Tinywan\Jwt\JwtToken;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
use const support\AUTH_CODE_NO;
use const support\USER_LOGIN_EXPIRE;

class MemberAuthCheckMiddleware implements MiddlewareInterface
{
    public function process(Request $request, callable $handler) : Response
    {
        // 解析用户令牌中的用户信息
        try {
            $memberId = JwtToken::getCurrentId();
        }catch (\Exception $e){
            return buildFail(AUTH_CODE_NO,'请先登录');
        }

        if (!$memberId) {
            // 未登录，抛出未授权异常
            return buildFail(AUTH_CODE_NO,'请先登录');
        }
        try {
            $exp=JwtToken::getTokenExp();
        }catch (\Exception $e){
            return buildFail(USER_LOGIN_EXPIRE,'登录已过期');
        }
        if ($exp<0) {
            // 登录已过期，抛出用户登录过期异常
            return buildFail(USER_LOGIN_EXPIRE,'登录已过期');
        }
        $request->member_id=(int)$memberId;
        return $handler($request);
    }
}